package com.yuyu.qingmangmall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.yuyu.common.exception.NotStockException;
import com.yuyu.common.to.mq.StockLockedTo;
import com.yuyu.common.to.mq.TaskDetailTo;
import com.yuyu.common.utils.PageUtils;
import com.yuyu.common.utils.Query;
import com.yuyu.common.utils.R;
import com.yuyu.qingmangmall.ware.dao.WareSkuDao;
import com.yuyu.qingmangmall.ware.entity.WareOrderTaskDetailEntity;
import com.yuyu.qingmangmall.ware.entity.WareOrderTaskEntity;
import com.yuyu.qingmangmall.ware.entity.WareSkuEntity;
import com.yuyu.qingmangmall.ware.feign.OrderFeignService;
import com.yuyu.qingmangmall.ware.feign.ProductFeignService;
import com.yuyu.qingmangmall.ware.service.WareOrderTaskDetailService;
import com.yuyu.qingmangmall.ware.service.WareOrderTaskService;
import com.yuyu.qingmangmall.ware.service.WareSkuService;
import com.yuyu.common.to.OrderTo;
import com.yuyu.qingmangmall.ware.vo.OrderItemVo;
import com.yuyu.qingmangmall.ware.vo.OrderVo;
import com.yuyu.qingmangmall.ware.vo.SkuHasStockVo;
import com.yuyu.qingmangmall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;



@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WareOrderTaskDetailService taskDetailService;

    @Autowired
    WareOrderTaskService taskService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderFeignService orderFeignService;


    private void unLockStock(Long skuId ,Long wareId ,Integer num ,Long taskDetailId){
        this.baseMapper.updateLocked(skuId,wareId,num);
        WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity();
        taskDetailEntity.setId(taskDetailId);
        taskDetailEntity.setLockStatus(2); // 1-已锁定  2-已解锁  3-扣减
        taskDetailService.updateById(taskDetailEntity);
    }
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询商品库存
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
       /*
       wareId: 123,//仓库id
       skuId: 123//商品id
        */
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isNullOrEmpty(wareId)) {
            wrapper.eq("ware_id",wareId);
        }

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isNullOrEmpty(skuId)) {
            wrapper.eq("sku_id",skuId);
        }

        IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params),
                wrapper);


        return new PageUtils(page);
    }

    /**
     * 添加库存
     * @param skuId
     * @param skuNum
     * @param wareId
     */
    @Transactional
    @Override
    public void addStock(Long skuId, Integer skuNum, Long wareId) {
//        WareSkuEntity wareSkuEntity = new WareSkuEntity();
//        wareSkuEntity.setSkuId(skuId);
//        wareSkuEntity.setWareId(wareId);
//        wareSkuEntity.setStock(skuNum);
//        this.baseMapper.update(wareSkuEntity,
//                new UpdateWrapper<WareSkuEntity>().eq("sku_id",skuId).eq("ware_id",wareId));

        List<WareSkuEntity> wareSkuList = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>()
                .eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuList.size()==0){
            // 仓库没有该条件的sku 新增数据库
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            // TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            // 做法一 自己catch异常
            // TODO 还可以用什么办法让异常出现以后不回滚？ 高级
            try {
                R skuInfo = productFeignService.info(skuId); //  skuInfo :SkuInfoEntity
                Map<String,Object> skuData = (Map<String, Object>) skuInfo.get("skuInfo");
                String skuName = (String) skuData.get("skuName");
                wareSkuEntity.setSkuName(skuName);
            } catch (Exception e){
                e.printStackTrace();
            }

            this.baseMapper.insert(wareSkuEntity);
        }else {
            // 仓库有该条件的sku 更新数据库
            this.baseMapper.addStock(skuId, skuNum, wareId);
        }
    }

    /**
     * 返回商品库存
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> stockVos = new ArrayList<SkuHasStockVo>();
        for (Long skuId : skuIds) {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            // 查询当前sku的总库存量
            Long stock = this.baseMapper.selectSkuStock(skuId);
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(stock != null && stock > 0); // stock>0  stock==null?false:stock>0
            stockVos.add(skuHasStockVo);
        }

        return stockVos;
    }

    /**
     * 为某个订单锁定库存
     * (rollbackFor = NotStockException.class)
     * @Transactional:默认出现运行时异常时回滚
     * @param wareSkuLockVo
     * 库存解锁的场景
     * 1. 下订单成功，订单过期没有支付被系统自动取消，被用户手动取消，都要解锁库存
     *
     * 2. 下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚
     *      之前锁定的库存就要自动解锁。
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {

        // 创建一个工作单，并将订单号保存至工作单
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        taskService.save(taskEntity);
        // 1.找到下单的收获地址，找到一个就近仓库，锁定库存
        // 1. 找到每个商品在那个仓库有库存
        List<OrderItemVo> locks = wareSkuLockVo.getLocks();
        List<SkuWareHasStock> wareHasStocks = locks.stream().map(item -> {
            SkuWareHasStock wareHasStock = new SkuWareHasStock();
            wareHasStock.setSkuId(item.getSkuId());
            wareHasStock.setNum(item.getCount());
            WareSkuDao wareSkuDao = this.baseMapper;
            // 查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(item.getSkuId());
            wareHasStock.setWareId(wareIds);
            return wareHasStock;
        }).collect(Collectors.toList());

        // 2.锁定库存
        for (SkuWareHasStock wareHasStock : wareHasStocks) {
            Boolean skuStocked = false; // 当前商品是否成功锁定库存
            Long skuId = wareHasStock.getSkuId();
            Integer num = wareHasStock.getNum();
            List<Long> wareIds = wareHasStock.getWareId();
            if (wareIds==null || wareIds.size()<1){
                // 所有仓库都没有该商品库存
                throw new NotStockException(skuId);
            }
            // 1.如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录给MQ
            // 2.锁定失败。前面保存的工作单信息就回滚了。发送出去的消息，即使要解锁记录，由于数据库查不到id，所以就不用解锁
            //
            for (Long wareId : wareIds) {
                // 尝试在该仓库锁定该商品的购买量
                // 锁定成功返回 1 ，失败返回 0
                Long count =  this.baseMapper.lockSkuStock(skuId,num,wareId);
                if (count==1L){
                    // 库存锁定成功
                    skuStocked = true;
                    // TODO 告诉MQ库存锁定成功
                    // lockStatus  1-已锁定  2-已解锁  3-扣减
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "", num, taskEntity.getId(), wareId, 1);
                    taskDetailService.save(taskDetailEntity);

                    StockLockedTo stockLockedTo = new StockLockedTo();
                    TaskDetailTo taskDetailTo = new TaskDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity,taskDetailTo);

                    stockLockedTo.setTaskId(taskEntity.getId());
                    // 只发id不行防止回滚找不到数据
                    stockLockedTo.setDetail(taskDetailTo);

                    rabbitTemplate.convertAndSend("stock-event-exchange",
                            "stock.locked",stockLockedTo);
//                    rabbitTemplate.convertAndSend("order-event-exchange",
//                            "order.create.order",orderEntity);

                    break;
                }
//                else {
                    // 当前仓库锁失败，继续下一个仓库
//                }
            }
            if (!skuStocked){
                // 当前商品锁定库存失败
                throw new NotStockException(skuId);
            }
        }


        return true;
    }

    // 被动补偿逻辑
    @Transactional
    @Override
    public void unlockStock(StockLockedTo stockLockedTo) {
        Long taskId = stockLockedTo.getTaskId();
        TaskDetailTo detail = stockLockedTo.getDetail();

        // 解锁：订单情况
        //  查询数据库关于这个订单的锁定库存信息
        //    1.没有这个订单。必须解锁。
        //    2.有这个订单。不是解锁库存。
        //       订单状态：已取消；解锁库存
        //               没取消；不能解锁库存
        // 没有，库存锁定失败，库存回滚，这种情况无需解锁
        WareOrderTaskEntity orderTask = taskService.getById(taskId);
        WareOrderTaskDetailEntity taskDetailEntity = taskDetailService.getById(detail.getId());
        if (orderTask!=null){
            // 解锁
            // R.ok().put("order", order)
            R r = orderFeignService.getInfoByOrderSn(orderTask.getOrderSn());
            if (r.getCode()==0){
                OrderVo order = r.getData("order", new TypeReference<OrderVo>() {
                });
                // status 订单状态【0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单】
                if (order==null || order.getStatus()==4){
                    // 订单回滚  或 订单状态为已关闭 都要解锁库存
                    if (taskDetailEntity.getLockStatus() == 1) {
                        // 1-已锁定  2-已解锁  3-扣减
                        // 只有已锁定状态才进行锁定
                        unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detail.getId());
                    }

                }
            }else {
                // 出现问题，消息拒绝接受，并重新放到队列中
                throw new RuntimeException("远程调用订单服务失败，重新解锁");
            }

        }else {
            // 不解锁

        }
    }

    // 主动解锁库存逻辑
    // 防止订单服务卡顿，导致订单状态消息一致改不了。库存消息优先到期。查询订单状态是新建状态，什么都不做就走了。
    // 导致卡顿的订单，永远不能解锁库存
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        // 查一下最新库存的状态，防止重复解锁库存
        WareOrderTaskEntity orderTaskEntity = taskService.getByOrderSn(orderTo.getOrderSn());
        // 按照工作单找到所有没有解锁的库存 进行解锁 （如果该服务卡顿，延迟队列的服务成功解锁库存，则无需重复解锁库存）
        List<WareOrderTaskDetailEntity> taskDetails = taskDetailService.getBaseByTaskId(orderTaskEntity.getId());
        for (WareOrderTaskDetailEntity taskDetail : taskDetails) {
            if (taskDetail.getLockStatus() == 1) {
                // 如果库存情况为已锁定，那么则解锁库存
                // Long skuId ,Long wareId ,Integer num ,Long taskId
                unLockStock(taskDetail.getSkuId(),taskDetail.getWareId(),taskDetail.getSkuNum(),taskDetail.getId());
            }
        }
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}